package nimy.info.android.dinnertime;

import info.nimy.google.recipesearch.html.RecipeItem;
import nimy.info.android.dinnertime.adapter.CustomFragmentStatePageAdater;
import nimy.info.android.dinnertime.model.RecipeKeyword;
import nimy.info.android.dinnertime.page.RecipeKeywordPage;
import nimy.info.android.dinnertime.page.RecipeListPage;
import nimy.info.android.dinnertime.page.TabIndicatorLineView;
import nimy.info.android.dinnertime.page.WebViewPage;
import nimy.info.android.dinnertime.utils.Utils;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

@SuppressLint("NewApi")
public class HomeActivity extends SherlockFragmentActivity {

	private static final String TAG = HomeActivity.class.getName();

	private static final int PAGE_DEFAULT = 0;
	private static final int PAGE_NUMBERS = 2;

	public static final boolean DEBUG = true;

	private static HomeActivity instance;

	private ViewPager mPager;
	private CustomFragmentStatePageAdater mPagerAdapter;
	private TabIndicatorLineView mLine;

	public static final int THEME = R.style.Theme_Sherlock_Light;
	// model
	private String currentRecipeKeyword;
	private boolean prepared = false;

	// -----------------------------------------------------------------------------
	private TabHost mTabHost;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_PROGRESS);
		setContentView(R.layout.fragment_tabs_pager);
		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup();
		initViewPager(PAGE_NUMBERS, 0xFFFF0000, 0xFF000000);
		// hide the action bar
		customLookFeelActionBar();
		getSupportActionBar().hide();
		instance = this;
	}

	private void initViewPager(int pageCount, int backgroundColor, int textColor) {
		mPager = (ViewPager) findViewById(R.id.pager);
		mPagerAdapter = new CustomFragmentStatePageAdater(this, mPager,
				mTabHost);
		mPager.setAdapter(mPagerAdapter);

		// display the tab or not
		mTabHost.getTabWidget().setVisibility(View.GONE);

		// mPagerAdapter.addTab(mTabHost.newTabSpec("loading_indicator")
		// .setIndicator("Loading"), LoadingIndicatorFragment.class, null);

		mPagerAdapter.addTab(
				mTabHost.newTabSpec(Constants.TAB_RECIPE_KEYWORD_TAG)
						.setIndicator("Keywords"), RecipeKeywordPage.class,
				null);
		mPagerAdapter.addTab(mTabHost.newTabSpec(Constants.TAB_RECIPE_LIST_TAG)
				.setIndicator("Recipes"), RecipeListPage.class, null);
		mPagerAdapter.addTab(
				mTabHost.newTabSpec(Constants.TAB_RECIPE_WEBPAGE_TAG)
						.setIndicator("Recipe Show"), WebViewPage.class, null);

		mPager.setCurrentItem(PAGE_DEFAULT);
		mPager.setPageMargin(1);

		// Display the bottom line as another indicator
		mLine = (TabIndicatorLineView) findViewById(R.id.line);
		mLine.setViewPager(mPager);
		mLine.setmTabHost(mTabHost);
	}

	private void customLookFeelActionBar() {
		// This is a workaround for http://b.android.com/15340 from
		// http://stackoverflow.com/a/5852198/132047
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
			BitmapDrawable bg = (BitmapDrawable) getResources().getDrawable(
					R.drawable.bg_striped);
			bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
			getSupportActionBar().setBackgroundDrawable(bg);

			BitmapDrawable bgSplit = (BitmapDrawable) getResources()
					.getDrawable(R.drawable.bg_striped_split_img);
			bgSplit.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
			getSupportActionBar().setSplitBackgroundDrawable(bgSplit);
		}
	}

	private void overlayActionBar() {
		requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
		getSupportActionBar().setBackgroundDrawable(
				getResources().getDrawable(R.drawable.ab_bg_black));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// inflateMenus(menu);
		// SubMenu sub = menu.addSubMenu("Theme");
		// sub.add(0, R.style.Theme_Sherlock, 0, "Default");
		// sub.add(0, R.style.Theme_Sherlock_Light, 0, "Light");
		// sub.add(0, R.style.Theme_Sherlock_Light_DarkActionBar, 0,
		// "Light (Dark Action Bar)");
		// sub.getItem().setShowAsAction(
		// MenuItem.SHOW_AS_ACTION_ALWAYS
		// | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home || item.getItemId() == 0) {
			return false;
		}
		setTheme(item.getItemId());
		if (Constants.DEBUG) {
			Log.d(TAG, "Change application theme to " + item.getItemId());
		}
		return true;
	}

	/**
	 * build the back order at different page
	 * 
	 * @return
	 */
	private int buildTabBackStack() {
		int currentItem = mPager.getCurrentItem();
		switch (currentItem) {
		case Constants.TAB_RECIPE_WEBPAGE:
			return Constants.TAB_RECIPE_LIST;
		case Constants.TAB_RECIPE_LIST:
			return Constants.TAB_RECIPE_KEYWORD;
		default:
			return -1;
		}
	}

	@Override
	public void onBackPressed() {
		int pageItem = buildTabBackStack();
		if (pageItem < 0) {
			this.showQuitDialog();
		} else {
			mPager.setCurrentItem(pageItem);
		}
	}

	public void inflateMenus(Menu menu) {
		/** Create an option menu from res/menu/items.xml */
		getSupportMenuInflater().inflate(R.menu.items, menu);

		/** Get the action view of the menu item whose id is search */
		View v = (View) menu.findItem(R.id.search).getActionView();

		/** Get the edit text from the action view */
		EditText txtSearch = (EditText) v.findViewById(R.id.txt_search);

		/** Setting an action listener */
		txtSearch.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				Toast.makeText(getBaseContext(), "Search : " + v.getText(),
						Toast.LENGTH_SHORT).show();
				return false;
			}
		});
	}

	private void checkNetwork() {
		if (!Utils.isNetworkConnected(HomeActivity.this)) {
			setPrepared(false);
			AlertDialog alertDialog = new AlertDialog.Builder(HomeActivity.this)
					.setTitle(R.string.applicaiton_no_network_alert)
					.setMessage(R.string.applicaiton_no_network_message)
					.setPositiveButton(R.string.applicaiton_no_network_config,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									Utils.gotoConfigureConnection(HomeActivity.this);
								}
							})
					.setNegativeButton(R.string.applicaiton_no_network_quit,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									HomeActivity.this.finish();
								}
							}).create();
			alertDialog.setCancelable(false);
			alertDialog.show();
		} else {
			setPrepared(true);
			endSplash();
		}
	}

	private void showQuitDialog() {
		AlertDialog alertDialog = new AlertDialog.Builder(HomeActivity.this)
				.setTitle(R.string.applicaiton_quit)
				.setMessage(R.string.applicaiton_message)
				.setPositiveButton(R.string.applicaiton_option_yes,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								HomeActivity.this.finish();
							}
						})
				.setNegativeButton(R.string.applicaiton_option_cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								return;
							}
						}).create();
		// avoid the back button closing it
		alertDialog.setCancelable(false);
		alertDialog.show();
	}

	public ViewPager getPager() {
		return mPager;
	}

	@Override
	protected void onResume() {
		checkNetwork();
		super.onResume();
	}

	public String getCurrentRecipeKeyword() {
		return currentRecipeKeyword;
	}

	public void setCurrentRecipeKeyword(String currentRecipeKeyword) {
		this.currentRecipeKeyword = currentRecipeKeyword;
	}

	public boolean isPrepared() {
		return prepared;
	}

	public void setPrepared(boolean prepared) {
		this.prepared = prepared;
	}

	public void showPage(int page) {
		getPager().setCurrentItem(page);
	}

	public void searchRecipes(final String name) {
		mPager.setCurrentItem(Constants.TAB_RECIPE_LIST);
		RecipeListPage page = getRecipeListPage();
		page.search(new RecipeKeyword(name, 0));
	}

	public void openWebViewForRecipe(final RecipeItem item) {
		mPager.setCurrentItem(Constants.TAB_RECIPE_WEBPAGE);
		WebViewPage page = getWebViewPage();
		page.loadRecipeItem(item);
	}

	public RecipeListPage getRecipeListPage() {
		return (RecipeListPage) getSupportFragmentManager().findFragmentByTag(
				Constants.TAB_RECIPE_LIST_TAG);
	}

	public WebViewPage getWebViewPage() {
		return (WebViewPage) getSupportFragmentManager().findFragmentByTag(
				Constants.TAB_RECIPE_WEBPAGE_TAG);
	}

	public static final HomeActivity getApplicaiton() {
		return instance;
	}

	public void setAppTitle(String name) {
		getSupportActionBar().setTitle(name);
	}

	public void resetAppTitle() {
		getSupportActionBar().setTitle(
				getResources().getString(R.string.app_name));
	}

	public void showErrorMessage(int stringId) {
		Utils.toastAtCenter(this, getResources().getString(stringId),
				Toast.LENGTH_LONG);
	}

	public void showErrorMessage(final String directlyString) {
		Utils.toastAtCenter(this, directlyString, Toast.LENGTH_LONG);
	}

	public void endSplash() {
		if (isPrepared()) {
			View maskView = findViewById(R.id.LoadingCoverLayout);
			if (maskView != null) {
				maskView.setVisibility(View.GONE);
			}

			ActionBar supportActionBar = getSupportActionBar();
			if (supportActionBar != null) {
				supportActionBar.show();
			}
		}
	}

}
